package cd.cdyb.sms.task;


import cd.cdyb.sms.dao.MessageRecordingDao;
import cd.cdyb.sms.domain.MessageRecording;
import cd.cdyb.sms.dto.MessageResponse;
import cd.cdyb.sms.service.InventoryService;
import cd.cdyb.sms.service.SmsService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class MessageScheduledTask {

    @Resource
    private SmsService smsService;

    @Resource
    private MessageRecordingDao messageRecordingDao;

    @Resource
    private InventoryService inventoryService;


    @Scheduled(cron = "0/15 * * * * ?")
    public void updateInventory() {

        log.info("-----------发送记录处理任务开始------------");
        LambdaQueryWrapper<MessageRecording> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MessageRecording::getStatus, 0);
        List<MessageRecording> messageRecordingList = messageRecordingDao.selectList(wrapper);
        List<MessageRecording> newMessageRecordingList = new ArrayList<>();
        List<String> timeoutMessageRecordingList = new ArrayList<>();
        Map<String, Integer> type5Map = new HashMap<>();
        Map<String, Integer> type6Map = new HashMap<>();

        for (MessageRecording messageRecording : messageRecordingList) {
            LocalDateTime createTime = messageRecording.getCreateTime();
            LocalDateTime now = LocalDateTime.now();
//            LocalDateTime beforeTime = now.minusMinutes(3);
            LocalDateTime beforeTime = now.minusDays(3);

            if (createTime.isBefore(beforeTime)) {
                timeoutMessageRecordingList.add(messageRecording.getNumber());

                String companyKey = messageRecording.getCompanyKey();
                //返还库存封装
                if (5 == messageRecording.getType()) {
                    if (type5Map.containsKey(companyKey)) {
                        Integer count = type5Map.get(companyKey);
                        count += messageRecording.getUseCount();
                        type5Map.put(companyKey, count);
                    } else {
                        type5Map.put(companyKey, messageRecording.getUseCount());
                    }
                } else if (6 == messageRecording.getType()) {
                    if (type6Map.containsKey(companyKey)) {
                        Integer count = type6Map.get(companyKey);
                        count += messageRecording.getUseCount();
                        type6Map.put(companyKey, count);
                    } else {
                        type6Map.put(companyKey, messageRecording.getUseCount());
                    }
                }
            } else {
                newMessageRecordingList.add(messageRecording);
            }
        }

        List<String> successList = new ArrayList<>();
        List<MessageRecording> failList = new ArrayList<>();
        List<MessageResponse> newMessageList = smsService.findNewMessageListWithNew();
        if (!CollectionUtils.isEmpty(newMessageList)) {
            for (MessageResponse messageResponse : newMessageList) {
                String task_no = messageResponse.getTask_no();
                for (MessageRecording messageRecording : newMessageRecordingList) {
                    String taskNo = messageRecording.getTaskNo();
                    //失败的要返还库存
                    String companyKey = messageRecording.getCompanyKey();

                    if (StringUtils.isEmpty(taskNo)){
                        //异常失败的数据返还库存封装
                        if (5 == messageRecording.getType()) {
                            if (type5Map.containsKey(companyKey)) {
                                Integer count = type5Map.get(companyKey);
                                count += messageRecording.getUseCount();
                                type5Map.put(companyKey, count);
                            } else {
                                type5Map.put(companyKey, messageRecording.getUseCount());
                            }
                        } else if (6 == messageRecording.getType()) {
                            if (type6Map.containsKey(companyKey)) {
                                Integer count = type6Map.get(companyKey);
                                count += messageRecording.getUseCount();
                                type6Map.put(companyKey, count);
                            } else {
                                type6Map.put(companyKey, messageRecording.getUseCount());
                            }
                        }
                        failList.add(messageRecording);
                        log.info("远程No[{}], 本地No[{}],本地手机号[{}]", task_no, taskNo, messageRecording.getPhone());
                        continue;
                    }
                    if (taskNo.equals(task_no)) {
                        String mobile = messageResponse.getMobile();
                        String phone = messageRecording.getPhone();
                        if (mobile.equals(phone)) {
                            String status_message = messageResponse.getStatus_message();
                            log.info("短信记录[{}], [{}]", taskNo, status_message);
                            if ("DELIVRD".equals(status_message)) {
                                if (!successList.contains(messageRecording.getNumber())){
                                    successList.add(messageRecording.getNumber());
                                }
                            } else {
                                String smsIndex = messageResponse.getSmsIndex();
                                if ("2".equals(smsIndex)) {
                                    log.info("当前是失败的且第二个记录跳过, 短信记录[{}], [{}]", taskNo, status_message);
                                    continue;
                                }
                                messageRecording.setStatus(2);
                                messageRecording.setFailReason(status_message);
                                failList.add(messageRecording);



                                //返还库存封装
                                if (5 == messageRecording.getType()) {
                                    if (type5Map.containsKey(companyKey)) {
                                        Integer count = type5Map.get(companyKey);
                                        count += messageRecording.getUseCount();
                                        type5Map.put(companyKey, count);
                                    } else {
                                        type5Map.put(companyKey, messageRecording.getUseCount());
                                    }
                                } else if (6 == messageRecording.getType()) {
                                    if (type6Map.containsKey(companyKey)) {
                                        Integer count = type6Map.get(companyKey);
                                        count += messageRecording.getUseCount();
                                        type6Map.put(companyKey, count);
                                    } else {
                                        type6Map.put(companyKey, messageRecording.getUseCount());
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        //对已发送成功的进行处理
        if (!CollectionUtils.isEmpty(successList)) {
            int batchSize = 1000; // 每个批次的大小
            int size = successList.size();
            log.info("success批量处理发送记录,总数量[{}]", size);

            for (int i = 0; i < size; i += batchSize) {
                List<String> list = successList.subList(i, Math.min(i + batchSize, size));
                log.info("success批量处理发送记录[{}]", list.size());
                // 批量更新
                messageRecordingDao.updateSuccessMessageRecordingByNumber(list);
            }
        }

        //对已发送失败的进行处理
        if (!CollectionUtils.isEmpty(failList)) {
            for (MessageRecording messageRecording : failList) {
                messageRecordingDao.updateMessageRecordingByNumber(messageRecording.getNumber(), messageRecording.getStatus(), messageRecording.getFailReason());
            }
        }

        //对超时的进行处理
        if (!CollectionUtils.isEmpty(timeoutMessageRecordingList)) {
            int batchSize = 1000; // 每个批次的大小
            int size = timeoutMessageRecordingList.size();
            log.info("批量处理发送记录,总数量[{}]", size);
            for (int i = 0; i < size; i += batchSize) {
                List<String> list = timeoutMessageRecordingList.subList(i, Math.min(i + batchSize, size));
                log.info("批量处理发送记录[{}]", list.size());
                // 批量更新
                messageRecordingDao.updateTimeoutMessageRecordingByNumber(list);

            }
        }
        log.info("全部批量处理发送记录处理完毕");

        // 返还库存
        if (!CollectionUtils.isEmpty(type5Map)) {
            for (Map.Entry<String, Integer> entry : type5Map.entrySet()) {
                log.info("5-[{}]补充库存[{}]", entry.getKey(), entry.getValue());
                inventoryService.increaseInventory(entry.getKey(), entry.getValue(), 5);
            }
        }

        if (!CollectionUtils.isEmpty(type6Map)) {
            for (Map.Entry<String, Integer> entry : type6Map.entrySet()) {
                log.info("6-[{}]补充库存[{}]", entry.getKey(), entry.getValue());
                inventoryService.increaseInventory(entry.getKey(), entry.getValue(), 6);
            }
        }
        log.info("-----------发送记录处理任务结束------------");
    }

    public static void main(String[] args) {
findFileData();
    }
    public static List<MessageResponse> findFileData() {
        try {
// 创建一个BufferedReader对象来读取txt文件

            BufferedReader reader = new BufferedReader(new FileReader("F:\\barcode\\txt1.txt"));
            String line;
            StringBuilder content = new StringBuilder();
            //逐行读取txt,文件的内容并存储到字符串中
            List<MessageResponse> list = new ArrayList<>();
            List<String> nameList = new ArrayList<>();
            while ((line = reader.readLine()) != null) {
                if (line.contains("15319223240")){
                    System.out.println(line);
                }
                if (line.contains("实际获取的数据")) {
                    int i = line.indexOf("[{");
                    String data = line.substring(i + 1, line.length() - 1);
                    int s1 = data.indexOf("data=[");
                    int s2 = data.indexOf("]");
                    data = data.substring(s1 + 6, s2);
                    String[] split = data.split("\\{");
                    for (String s : split) {
                        if (!StringUtils.isEmpty(s)) {
                            int n1 = data.indexOf("task_no") + 8;
                            int n2 = data.indexOf("status_message") - 2;
                            String task_no = data.substring(n1, n2);

                            if (nameList.contains(task_no)) {
                                continue;
                            }
                            nameList.add(task_no);
                            int n3 = data.indexOf("status_message") + 15;
                            int n4 = data.indexOf("message_info") - 2;

                            String status_message = data.substring(n3, n4);

                            int n5 = data.indexOf("mobile") + 7;
                            int n6 = data.indexOf("msg_id") - 2;
                            String mobile = data.substring(n5, n6);
                            MessageResponse messageResponse = new MessageResponse();
                            messageResponse.setMobile(mobile);
                            messageResponse.setStatus_message(status_message);
                            messageResponse.setTask_no(task_no);
                            list.add(messageResponse);
                        }
                    }
                }
            }
//关闭BufferedReader对象
            reader.close();

            return list;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return new ArrayList<>();
    }
}
